package com.tianji.promotion.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.domain.query.CodeQuery;
import com.tianji.promotion.domain.vo.ExchangeCodeVo;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.tianji.promotion.constants.Constants.COUPON_CODE_MAP_KEY;
import static com.tianji.promotion.constants.Constants.COUPON_CODE_SERIAL_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author LYQ
 * @since 2024-07-03
 */
@Service
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {
    private final StringRedisTemplate redisTemplate;
    private final BoundValueOperations<String, String> serialOps;

    public ExchangeCodeServiceImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.serialOps = redisTemplate.boundValueOps(COUPON_CODE_SERIAL_KEY);
    }

    /**
     * 调用线程池异步生成优惠券兑换码
     *
     * @param coupon
     */
    @Override
    @Async("generateExchangeCodeExecutor")
    public void asyncGenerateCode(Coupon coupon) {
        //1、获取发放数量
        Integer totalNum = coupon.getTotalNum();
        //2、修改redis自增序列号并获取原序列号
        Long result = serialOps.increment(totalNum);
        if (result == null) {
            return;//如果结果为空，则redis错误直接返回
        }
        try {
            //3、循环发放张数次数，生成对应数量的兑换码
            int maxSerialNum = result.intValue();
            List<ExchangeCode> list = new ArrayList<>(totalNum);
            for (int i = maxSerialNum - totalNum + 1; i <= maxSerialNum; i++) {
                ExchangeCode e = new ExchangeCode();
                String code = CodeUtil.generateCode(i, coupon.getId());
                list.add(e);
                e.setCode(code);
                e.setId(i);
                e.setExchangeTargetId(coupon.getId());
                e.setExpiredTime(coupon.getIssueEndTime());
            }
            //4、兑换码批量保存
            saveBatch(list);
        } catch (Exception e) {
            //保存异常则回滚redis自增序列号
            log.error("生成兑换码异常，回滚redis自增序列号,错误信息：", e);
            serialOps.decrement(totalNum);
        }
    }

    /**
     * 优惠券兑换码分页查询
     *
     * @param query
     */
    @Override
    public PageDTO<ExchangeCodeVo> queryExchangeCodePage(CodeQuery query) {
        //1、获取查询条件
        Integer status = query.getStatus();
        //2、分页搜索
        Page<ExchangeCode> pageResult = lambdaQuery()
                .select(ExchangeCode::getId, ExchangeCode::getCode)
                .eq(ExchangeCode::getExchangeTargetId, query.getCouponId())
                .eq(status != null, ExchangeCode::getStatus, status)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<ExchangeCode> records = pageResult.getRecords();
        //3、为空则返回空PageDTO
        if (ObjectUtils.isEmpty(records)) {
            return PageDTO.empty(pageResult);
        }
        //4、转为Vo
        List<ExchangeCodeVo> list = records.stream().map(e -> BeanUtils.copyBean(e, ExchangeCodeVo.class)).collect(Collectors.toList());
        //5、封装PageDTO返回
        return PageDTO.of(pageResult, list);
    }

    /**
     * 对应序列号的兑换码是否兑换
     *
     * @param serialNum
     * @param b
     */
    @Override
    public boolean updateExchangeMark(long serialNum, boolean b) {
        Boolean boo = redisTemplate.opsForValue().setBit(COUPON_CODE_MAP_KEY, serialNum, b);
        return boo != null && boo;
    }
}
